<script  setup >
import { defineProps, reactive, ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
defineProps({
  image: {
    type: Array,
    default: () => []
  }
})
const goodsIndex = ref(0)
const target = ref(null)
const { elementX, elementY, isOutside } = useMouseInElement(target)
const layerstyle = reactive({
  top: 0,
  left: 0
//   show: false
})

const largeStyle = reactive({
  'background-position-x': '0px',
  'background-position-y': '0px'
})
watch([elementX, elementY, isOutside], () => {
  let top = elementY.value - 100
  let left = elementX.value - 100

  if (top > 200) top = 200
  if (top < 0) top = 0
  if (left > 200) left = 200
  if (left < 0)left = 0
  layerstyle.top = top + 'px'
  layerstyle.left = left + 'px'
  //   layerstyle.show = true
  largeStyle['background-position-x'] = -2 * left + 'px'
  largeStyle['background-position-y'] = -2 * top + 'px'
})
</script>

<template>
  <div class="goods-image">
    <!-- 显示在右侧的放大之后的区域 -->
    <div class="large"
         v-show="!isOutside"
    :style="[{backgroundImage:`url(${image[goodsIndex]})`, ...largeStyle}]"></div>

    <div class="middle" ref="target">
      <img :src="image[goodsIndex]" />
      <!-- 移动遮罩 -->
      <div class="layer" v-show="!isOutside" :style="layerstyle"></div>
    </div>
    <ul class="small">
      <li v-for="(item,index) in image" :key="index" :class="{active: index === goodsIndex }" @mouseenter="goodsIndex=index">
        <img
          :src="item"
          alt=""
        />
      </li>
    </ul>
  </div>
</template>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    background-repeat: no-repeat;
    // 放大一倍
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0,0,0,.2);
      left: 0;
      top: 0;
      // 可以移动
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
